<template>
  <el-container style="height: 100%;">
    <el-main style="width: 100%;">
      <el-card class="box-card">
        <el-form :model="searchForm" inline class="search-form">
          <el-row :gutter="20" type="flex" justify="space-between" align="middle">
            <el-col :span="10">
              <el-form-item label="输入查询身份证号">
                <el-input v-model="searchForm.idNumber" placeholder="输入查询身份证号"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="search">查询</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item class="text-right">
                <el-button type="success" @click="dayin">打印申报表</el-button>
                <el-button type="success" @click="addPerson">新增人员</el-button>
                <el-button type="warning" @click="exportData">进入下一步单练报名</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="pagedData" v-if="true" style="width: 100%; height: 100%;" stripe class="border-table">
          <el-table-column prop="id" label="序号" width="50">
            <template #default="{ $index }">
              {{ $index+1 }}
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="姓名"></el-table-column>
          <el-table-column prop="idcard" label="证件号码"></el-table-column>
          <el-table-column prop="birthday" label="出生年月"></el-table-column>
          <el-table-column prop="sex" label="性别"></el-table-column>
          <el-table-column prop="phone" label="手机号码"></el-table-column>
          <el-table-column label="参赛组别">
            <template #default="{ row }">
              <span v-if="row.matchesGroupId">{{ staffgroup(row.matchesGroupId) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="照片">
            <template v-slot="scope">
              <img :src="serverUrl + scope.row.image" style="width: 90px; height: auto;" alt="照片"
                @error="handleImageError">
            </template>
          </el-table-column>
          <el-table-column prop="content" label="难度、内容填报">
            <template #default="{ row }">
              <el-button type="primary" :bg="true" link @click="fetchroutine(row.id)">点击填报</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button :bg="true" link @click="edit(row.id)">修改</el-button>
              <el-button :bg="true" link @click="deleter(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="end" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="currentPage" :page-sizes="[4]" :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </el-card>
    </el-main>
  </el-container>
  <el-dialog title="修改信息" v-model="dialogVisible" width="30%" @close="dialogVisible = false">
    <el-form :model="editForm">
      <el-form-item label="姓名">
        <el-input v-model="editForm.userName" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="editForm.idcard" placeholder="请输入身份证号"></el-input>
      </el-form-item>
      <el-form-item label="出生年月">
        <el-input v-model="editForm.birthday" placeholder="请输入出生年月"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-input v-model="editForm.sex" placeholder="请输入性别"></el-input>
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input v-model="editForm.phone" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item label="参赛组别">
        <el-select v-model="editForm.matchesGroupId" placeholder="请选择参赛组别">
          <el-option v-for="group in groups" :key="group.id" :label="group.groupname" :value="group.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="照片">
        <el-upload class="avatar-uploader" action="http://back1.idcfengye.com:15173/competition/upload" :show-file-list="false"
          :http-request="customUpload" :before-upload="beforeUpload">
          <img v-if="editForm.image" :src="serverUrl + editForm.image" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          <el-button link icon="el-icon-delete" @click="deletePhoto" v-if="editForm.image">删除照片</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEdit">提交修改</el-button>
    </span>
  </el-dialog>
  <el-dialog title="查看代码" v-model="dialogVisiblecode" width="50%" @close="dialogVisiblecode = false">
    <el-form-item label="项目名称" style="margin: 20px;">
      <el-select v-model="encodeid" placeholder="请选择">
        <el-option v-for="item in encode" :key="item.id" :label="`${projectMap[item.projectId]}(${item.memos})`"
          :value="item.routineid"></el-option>
      </el-select>
    </el-form-item>
    <span class="dialog-footer">
      <el-button @click="dialogVisiblecode = false">关闭</el-button>
      <el-button type="primary" @click="Provisionsdeclaration">前往难度申报</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watchEffect, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';
import { useTeamStore } from '../store/teamgroupid.js';
import defaultImagePath from '../assets/th.jpg'; // 导入默认图片路径

const teamStore = useTeamStore();
const router = useRouter();

const teamid = teamStore.teamGroupId;

const encode = ref([]);
const encodeid = ref([]);

const searchForm = ref({
  idNumber: ''
});
const addxiugai = ref({})

const dialogVisible = ref(false);
const editForm = ref({});

const currentPage = ref(1);
const pageSize = ref(4);
const total = ref(0);

const groups = ref([]);

const projects =  ref([]);

const noimage = ref('');
// 使用ref创建一个反应性变量来存储过滤后的工作人员列表
const filteredStaffs = ref([]);

const dialogVisiblecode = ref(false);

const matchid = ref(localStorage.getItem('matchId'));
const token = localStorage.getItem('userToken');

///获取当前比赛的组别信息
async function fetchgroup() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/matchgroup/${matchid.value}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    groups.value = response.data.matchgroup;
  } catch (error) {
    console.error(error);
  }
}

fetchgroup();

// 获取当前比赛的项目信息
async function fetchproject() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/project/${matchid.value}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });    
    projects.value = response.data.project;
  } catch (error) {
    console.error(error);
  }
}

fetchproject();

//获取该用户项目申报编码
async function fetchroutine(userid) {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/routineid/${userid}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    encode.value = response.data.data;
  } catch (error) {
    console.error(error);
  }
  dialogVisiblecode.value = true;
}

// 根据组别id获取组别名称
const staffgroup = (id) => {
  const item = groups.value.find(group => group.id === id);
  return item ? item.groupname : '';
}
// 使用computed计算属性来计算分页数据
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const page_data = filteredStaffs.value.slice(start, start + pageSize.value);
  return page_data || [];
});

// 定义服务器的 URL
const serverUrl = ref('http://back1.idcfengye.com:15173');
teamStore.staffs = [];
// 处理图片加载失败的逻辑
function handleImageError(event) {
  event.target.src = defaultImagePath;
}

// 监听 searchForm 的变化，并更新 filteredStaffs
watchEffect(() => {
  const idNumber = searchForm.value.idNumber || '';
  filteredStaffs.value = teamStore.staffs.filter(staff => {
    const idcard = staff.idcard || '';
    return idcard.includes(idNumber);
  });
  total.value = filteredStaffs.value.length;
});

// 分页方法
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 重置为第一页
};

// 分页方法
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

// 搜索方法，用于主动触发搜索
const search = () => {
  // 由于watchEffect已经监听了searchForm的变化，这里不需要额外的逻辑
  // 这个方法可以保持为空，或者你可以在这里执行其他与搜索相关的操作
};

//选择好项目前往难度申报页面
const Provisionsdeclaration = () => {
  console.log(encodeid.value);
  
  router.push({ path: '/home/Provisionsdeclaration', query: { routineid: encodeid.value } });
}


//获取某一团队成员:staff
async function edit(row) {
  addxiugai.value = row;
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/staff/byStaffId/${row}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    editForm.value = { ...response.data.staff };
    dialogVisible.value = true;
  } catch (error) {
    console.error(error);
  }
}


// 提交修改的方法
async function submitEdit() {
  // 验证姓名
  if (!editForm.value.userName) {
    ElMessage.error('姓名不能为空');
    return;
  }

  // 验证身份证号码
  if (/^[1-9]\d{17}[0-9X]$/.test(editForm.value.idcard)) {
    ElMessage.error('身份证号码不正确');
    return;
  }

  // 验证出生日期
  if (!editForm.value.birthday) {
    ElMessage.error('出生日期不能为空');
    return;
  }
  // 验证出生日期格式
  if (!/^\d{4}-\d{2}-\d{2}$/.test(editForm.value.birthday)) {
    ElMessage.error('出生日期格式不正确');
    return;
  }

  // 验证性别
  if (!editForm.value.sex) {
    ElMessage.error('性别不能为空');
    return;
  }

  // 验证手机号码
  if (!editForm.value.phone || !/^1\d{10}$/.test(editForm.value.phone)) {
    ElMessage.error('手机号码格式不正确');
    return;
  }

  // 验证参赛组别
  if (!editForm.value.matchesGroupId) {
    ElMessage.error('参赛组别不能为空');
    return;
  }

  try {
    const response = await axios.put(`http://back1.idcfengye.com:15173/competition/staff`, editForm.value, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    if (response.data.success) {
      ElMessage.success('修改成功');
      dialogVisible.value = false;
      // 可以在这里重新获取数据或刷新列表
    } else {
      ElMessage.error(response.data.msg || '修改失败');
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('修改失败');
  }
}

// 新增人员页面跳转
const addPerson = () => {
  router.push({ path: '/home/newpersonnel' });
};

//单练报名页面跳转
const exportData = () => {
  router.push({ path: '/home/solopractice' });
}

// 自定义上传方法
const customUpload = async (file) => {
  const formData = new FormData();
  formData.append('file', file.file);

  try {
    const response = await axios.post('http://back1.idcfengye.com:15173/competition/upload', formData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      }
    });
    if (response.data.success) {
      editForm.value.image = response.data.path;
      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error('图片上传失败');
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('图片上传失败');
  }
};

// 上传前的检查
const beforeUpload = (file) => {
  // 可以在这里添加文件类型和大小的检查
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件');
    return false;
  }
  // 可以添加文件大小的检查
  return isImage;
};


// 删除 '/upload/' 的函数
function removeUploadPath(filePath) {
  return filePath.replace('/upload/', '');
}

// 删除照片的方法
const deletePhoto = async () => {
  noimage.value = editForm.value.image;
  const cleanedImagePath = removeUploadPath(noimage.value);
  try {
    // 调用后端接口删除服务器上的照片
    await axios.delete(`http://back1.idcfengye.com:15173/competition/delete/${cleanedImagePath}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    // 从 editForm 中移除照片 URL
    editForm.value.image = '';
    ElMessage.success('照片删除成功');
  } catch (error) {
    console.error(error);
    if (error.code === 'ERR_NETWORK') {
      ElMessage.error('网络请求失败，请检查你的网络连接或服务器状态。');
    } else {
      ElMessage.error('删除失败：' + error.message);
    }
  }
}


// 删除方法
const deleter = (row) => {
  // 使用 ElMessageBox.confirm 弹出确认对话框
  ElMessageBox.confirm('确定要删除这条记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 用户点击确定后的逻辑
    axios.delete(`http://back1.idcfengye.com:15173/teamproject/${row}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    }).then(response => {
      // 处理响应
      if (response.data.success) {
        ElMessage.success('删除成功');
        // 可以在这里重新获取数据或刷新列表
        fetchTeamProjects(); // 假设你有一个方法来重新获取团队项目列表
      }
    }).catch(error => {
      // 处理错误
      console.error(error);
      ElMessage.error('删除失败');
    });
  }).catch(() => {
    // 用户点击取消后的逻辑
    ElMessage.info('删除操作已取消');
  });
};

//映射projectname给页面的peojdectid
const projectMap = computed(() => {
  const map = {};
  projects.value.forEach(p => {
    map[p.id] = p.projectName;
  });
  return map;
});

function dayin(){
  router.push({ path:'/home/hometeamapp', query: { teamid: teamid,matchid: matchid.value } });
}

onMounted(() => {
  teamStore.fetchteamgroupid(0);
});


</script>

<style scoped>
.avatar {
  width: 90px;
  height: 90px;
}

::v-deep .el-upload--picture-card {
  --el-upload-picture-card-size: 90px;
}

::v-deep .el-upload-list--picture-card {
  --el-upload-list-picture-card-size: 90px;
}

.el-container {
  height: 100%;
  /* 或者其他合适的高度 */
  overflow: auto;
  /* 当内容超出容器时显示滚动条 */
}

.box-card {
  background-color: #a3c9c7;
  display: block;
  width: 98%;
}

.search-form {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
  float: right;
}

.button-icon {
  height: 15px;
  margin-left: -5px;
  margin-top: auto;
}

.end {
  margin-top: 10px;
}
</style>